package com.itmk.system.permission.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itmk.config.redis.RedisUtils;
import com.itmk.constants.Constant;
import com.itmk.result.DataResult;
import com.itmk.system.common.entity.JsonData;
import com.itmk.system.common.service.RedisService;
import com.itmk.system.home.vo.MakeMenuTree;
import com.itmk.system.home.vo.TreeVo;
import com.itmk.system.permission.entity.Permission;
import com.itmk.system.permission.service.PermissionService;
import com.itmk.system.role.entity.Role;
import com.itmk.system.role_permission.entity.RolePermission;
import com.itmk.system.role_permission.mapper.RolePermissionMapper;
import com.itmk.system.role_permission.service.RolePermissionService;
import com.itmk.utils.JwtTokenUtil;
import com.itmk.vo.req.RolePermissionReqVO;
import com.itmk.vo.resp.PermissionRespVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/permission")
@Api(tags = "权限菜单模块")
public class PerssionController {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RolePermissionService rolePermissionService;

    /*
        根据Id删除菜单
     */
    @ApiOperation(value = "删除菜单接口")
    @RequestMapping(value = "deleteById", method = RequestMethod.POST)
    public JsonData deleteById(@RequestBody Permission permission, HttpServletRequest request) {
        boolean b = permissionService.removeById(permission.getId());
        if (b) {
            RedisUtils.ClearRedisMenu(request);
            return JsonData.buildSuccess("删除成功");
        } else {
            log.error("删除菜单失败");
            return JsonData.buildError("删除失败");
        }
    }

    /*
    根据Id查询菜单
     */
    @ApiOperation(value = "根据Id查询菜单接口")
    @RequestMapping(value = "queryPermissionById", method = RequestMethod.POST)
    public JsonData queryPermissionById(@RequestBody Permission permission) {
        Permission p = permissionService.getById(permission.getId());
        return JsonData.buildSuccess(p);
    }

    /**
     * 获取权限列表数据
     *
     * @return
     */
    @ApiOperation(value = "获取菜单全部数据接口")
    @RequestMapping(value = "/getMenuList", method = RequestMethod.POST)
    public JsonData getMenuList() {
        QueryWrapper<Permission> query = new QueryWrapper<>();
        query.lambda().orderByAsc(Permission::getOrderNum);
        List<Permission> list = permissionService.list();
        List<Permission> menuList = null;
        if (list.size() > 0) {
            menuList = MakeMenuTree.makeTree(list, 0L);
        }
        return JsonData.buildSuccess(menuList, "查询列表成功");
    }

    /**
     * 新增权限获取上级树数据
     *
     * @return
     */
    @ApiOperation(value = "获取上级节点目录树")
    @RequestMapping(value = "getParenList", method = RequestMethod.POST)
    public JsonData getParenList() {
        QueryWrapper<Permission> query = new QueryWrapper<>();
        query.lambda().eq(Permission::getType, "0").or().eq(Permission::getType, "1");
        List<Permission> list = permissionService.list(query);
        List<TreeVo> listTree = new ArrayList<>();
        TreeVo parentTree = new TreeVo();
        parentTree.setId(0L);
        parentTree.setPid(-1L);
        parentTree.setName("顶级菜单");
        ;
        parentTree.setOpen(true);
        parentTree.setChecked(false);
        listTree.add(parentTree);
        if (list.size() > 0) {
            for (Permission p : list) {
                if (p != null) {
                    TreeVo vo = new TreeVo();
                    vo.setId(p.getId());
                    vo.setPid(p.getParentId());
                    vo.setName(p.getLabel());
                    vo.setOpen(true);
                    vo.setChecked(false);
                    listTree.add(vo);
                }
            }
        }
        return JsonData.buildSuccess(listTree, "成功");
    }


    /**
     * addPermission
     *
     * @return
     */

    @ApiOperation(value = "增加一个菜单项")
    @RequestMapping(value = "/addPermission", method = RequestMethod.POST)
    public JsonData addPermission(@RequestBody Permission permission, HttpServletRequest request) {
        boolean b = permissionService.save(permission);
        if (b) {
            RedisUtils.ClearRedisMenu(request);
            return JsonData.buildSuccess(null, "新增权限成功!");
        } else {
            return JsonData.buildError("新增权限失败！");
        }

    }

    /**
     * 编辑权限保存
     *
     * @return
     */
    @RequestMapping(value = "editSave", method = RequestMethod.POST)
    @ApiOperation(value = "编辑菜单")
    public JsonData editSave(@RequestBody Permission permission, HttpServletRequest request) {
        boolean b = permissionService.updateById(permission);
        if (b) {
            RedisUtils.ClearRedisMenu(request);
            return JsonData.buildSuccess(null, "编辑成功!");
        } else {
            return JsonData.buildError("编辑失败!");
        }
    }



    /**
     * 获取权限列表数据
     *
     * @return
     */
    @ApiOperation(value = "获取授权树数据接口")
    @RequestMapping(value = "/getTreeNodeList", method = RequestMethod.POST)
    public DataResult getTreeNodeList(@RequestBody Role role) {
        QueryWrapper<Permission> query = new QueryWrapper<>();
        query.lambda().orderByAsc(Permission::getOrderNum);
//        获取系统中的全部权限
        List<Permission> allpermission = permissionService.list();
        List<PermissionRespVO> nodeList = new ArrayList<>();
//        获取当前角色的全部权限
        List<Permission> rolepermissions = permissionService.getPermissionListByRoleId(role.getId());
        List<Long> ids = rolepermissions.stream().filter(p -> p != null).map(p -> p.getId()).collect(Collectors.toList());
        if (allpermission.size() > 0) {
//            遍历所有系统权限，如果当前角色有这个权限那么选中
            for (Permission p : allpermission) {
                PermissionRespVO permissionRespVO = new PermissionRespVO();
                permissionRespVO.setId(p.getId());
                permissionRespVO.setPid(p.getParentId());
                permissionRespVO.setName(p.getLabel());
//                当权限类型是0主节点 或者是1 菜单时 打开折叠
                permissionRespVO.setOpen(p.getType().equals("0") || p.getType().equals("1") ? true : false);
//                设置初始化显示与否
                permissionRespVO.setChecked(ids.contains(p.getId()) ? true : false);
                nodeList.add(permissionRespVO);
            }
        }
        return DataResult.success(nodeList);
    }

    /**
     * 编辑角色权限保存
     *
     * @return
     */
    @RequestMapping(value = "updateRolePermission", method = RequestMethod.POST)
    @ApiOperation(value = "编辑角色权限")
    @Transactional
    public DataResult updateRolePermission(@RequestBody RolePermissionReqVO vo) {
        long b = permissionService.deletePermissionByRoleId(vo.getRoleId());
        if (b > 0) {
            List<Long> ids = (vo.getPermissionIds());
            List<RolePermission> rolePermissionList = new ArrayList<>();
            for (Long id : ids) {
                rolePermissionList.add(new RolePermission(vo.getRoleId(), id));
            }
            Boolean bo = this.rolePermissionService.saveBatch(rolePermissionList);
            if (bo) {
                return DataResult.success();
            } else {
                return DataResult.getResult(300100, "编辑失败!");
            }
        } else {
            return DataResult.getResult(300100, "编辑失败!");
        }
    }
}
